<?php
/**
 * Created by PhpStorm.
 * User: 87976
 * Date: 2018/1/25
 * Time: 14:05
 */

namespace App\Services\Album;


use App\Adapters\AlbumAdapter;
use App\Repositories\Album\AlbumTemplateRepository;
use App\Repositories\Album\AlbumRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class AlbumService
 * @package App\Services
 */
class AlbumService
{

    /**
     * @var AlbumRepository
     */
    protected $albumRepository;

    /**
     * @var AlbumTemplateRepository
     */
    protected $albumTemplateRepository;

    /**
     * AlbumService constructor.
     * @param AlbumRepository $albumRepository
     * @param AlbumTemplateRepository $albumTemplateRepository
     */
    public function __construct(AlbumRepository $albumRepository, AlbumTemplateRepository $albumTemplateRepository)
    {
        $this->albumRepository = $albumRepository;

        $this->albumTemplateRepository = $albumTemplateRepository;
    }

    /**
     * @author Jerry
     * @param int $id
     * @param int $isShow
     * @return array
     */
    public function handle(int $id, int $isShow)
    {
        $album = $this->albumRepository->findAlbumById($id, $isShow)->toArray();

        if (empty($album)) {
            throw new NotFoundHttpException('专辑已过期');
        }

        $templates = $this->albumTemplateRepository->findTemplateByAlbumId($album['id']);


        $templateData = $this->getTemplateData($templates);

        return [
            'name'  =>  $album['name'],
            'data'  =>  $templateData,
        ];
    }

    /**
     * @author Jerry
     * @param array $templates
     * @return array
     */
    protected function getTemplateData(array $templates)
    {
        if (empty($templates)) {
            throw new NotFoundHttpException('专辑内容为空');
        }

        $data = [];

        foreach ($templates as $key => $valule) {

            $template = $this->stencil($valule['type'])->handle($valule);

            if (empty($template)) {
                continue;
            }

            $data[] = $template;
        }

        return $data;
    }

    /**
     * @author Jerry
     * @param int $type
     * @return AlbumAdapter
     */
    protected function stencil(int $type)
    {
        return new AlbumAdapter($type);
    }
}